/**
 * Created by benny on 2016/9/22.
 */

var basePath        = "http://localhost:8989";
var $image_Carousel = $(".theme-panel");

// 模拟trigger 显示隐藏 主题按钮
var flag            = false;
var json;
var requestTableObj = {
    tableClassName: '<thead>' +
    '<tr>' +
    '<td class="success" colspan="7">',
    tableHeader   : '</td>' +
    '</tr>' +
    '<tr>' +
    '<td class="active text-center">序号</td> ' +
    '<td class="success">参数标识</td>' +
    '<td class="warning">参数名称</td> ' +
    '<td class="danger text-center">出现要求</td>' +
    '<td class="info">默认值</td>' +
    '<td class="success">描述</td>' +
    '<td class="warning">操作</td>' +
    '</tr> ' +
    '</thead>' +
    '<tbody> ',

    tableBody: '<tr>' +
    '<td>{0}</td>' +
    '<td class="active"><input class="form-control" type="text" value="{1}" readonly="readonly"/></td>' +
    '<td class="warning"><input class="form-control" type="text" value="{2}" readonly="readonly"/></td>' +
    '<td class="danger text-center" onclick="appearNecessary(this)">{3}</td>' +
    '<td class="info"><textarea class="form-control" readonly="readonly">{4}</textarea></td>' +
    '<td class="success"><textarea class="form-control" readonly="readonly">{5}</textarea> <!--<input class="form-control" type="text" value="{5}" readonly="readonly"/>--></td>' +
    '<td>' +
    '<span onclick="updateTd(this)" class="btn btn-warning glyphicon glyphicon-pencil"></span>' +
    '<span onclick="deleteTd(this)" class="btn btn-danger glyphicon glyphicon-remove"></span>' +
    '</td>' +
    '</tr>',
    type     : "request",
    className: "",
    dataParam: ""
}

var responseTableObj = {

    tableClassName: '<thead>' +
    '<tr>' +
    '<td class="success" colspan="6">',
    tableHeader   : '</td>' +
    '</tr>' +
    '<tr>' +
    '<td class="active">序号</td> ' +
    '<td class="success">参数标识</td>' +
    '<td class="warning">参数名称</td> ' +
    '<td class="danger text-center">出现要求</td>' +
    '<td class="success">描述</td>' +
    '<td class="warning">操作</td>' +
    '</tr> ' +
    '</thead>' +
    '<tbody> ',

    tableBody: '<tr>' +
    '<td>{0}</td>' +
    '<td class="success"><input class="form-control" type="text" value="{1}" readonly="readonly"/></td>' +
    '<td class="warning"><input class="form-control" type="text" value="{2}" readonly="readonly"/></td>' +
    '<td class="danger text-center" onclick="appearNecessary(this)">{3}</td>' +
    '<td class="info"><input class="form-control" type="text" value="{5}" readonly="readonly"/></td>' +
    '<td>' +
    '<span onclick="updateTd(this)" class="btn btn-warning glyphicon glyphicon-pencil"></span>' +
    '<span onclick="deleteTd(this)" class="btn btn-danger glyphicon glyphicon-remove"></span>' +
    '</td>' +
    '</tr>',
    type     : "reponse",
    className: "",
    dataParam: ""
}

var intervalId;

$(function () {

    $image_Carousel.hide();

    addRequired();

    $.ajax({
        type      : "get",
        url       : basePath + "/theme",
        dataType  : 'json',
        beforeSend: function (XMLHttpRequest) {
            intervalId = showLoading(0, 10);
        },
        success   : function (data) {
            if (data['result'] == "true") {
                json = data['data'];
                // 页面追加主题
                addImage(json);
                addDot(json);
            } else {
                console.info(data['msg']);
            }
        },
        complete  : function (XMLHttpRequest, textStatus) {
            hideLoading(intervalId);
        },
        error     : function () {
            //请求出错处理
        }
    });

    $("#changeTheme").on("click", function () {
        flag ? hide_image_Carousel() : show_image_Carousel();
    })

    /**
     * 阅览主题
     */
    $(document).on("mouseover", ".img-theme", function () {
        var themeName = $(this).attr("src");
        $("div.img-bg-prev").css("background-image", 'url(' + themeName + ')');
        $(this).css({opacity: '0.8', border: '2px dashed #06c'});
    }).on("mouseout", ".img-theme", function () {
        // 选中的图片对象
        var $imgChecked = $("div.img-bg div img[img-status='active']");
        // 取出选择的背景图片地址
        var themeName   = $imgChecked.attr("bgsrc");
        changeTheme(themeName);
        $(this).css({opacity: 1, border: 'none'});
        $imgChecked.css({opacity: '0.8', border: '2px solid #06c'});
    })

    /**
     * 确定阅览的主题
     */
    $(document).on("click", ".img-theme", function () {
        var themeName = $(this).attr("src");
        changeTheme(themeName);
        //取消之前选中的图片的样式和状态
        $("div.img-bg div img").not(this).css({opacity: 1, border: 'none'}).attr("img-status", "");
        //设置当前选中的图片的样式和状态
        $(this).css({opacity: '0.8', border: '2px solid #06c'});
        $(this).attr("img-status", "active").attr("bgsrc", themeName);
    })

    // 显示请求参数
    $("#requestParamBtn").on("click", function () {
        var intervalId            = showLoading(0, 10);
        var className             = $("#apiRequestParam").val();
        requestTableObj.className = className;
        getMethodParam(requestTableObj);
        hideLoading(intervalId);
    })

    /**
     * 设置鼠标滑过图片状态
     */
    function setMouseOverImgStatus(me) {
        $(me).css({opacity: '0.8', border: '2px dashed #06c'});
    }

    /**
     * 清除鼠标滑过图片状态
     */
    function setMouseOverImgStatus() {

    }

    // 显示响应参数
    $("#responseParamBtn").on("click", function () {
        var intervalId             = showLoading(0, 10);
        var className              = $("#apiResponseParam").val();
        responseTableObj.className = className;
        getMethodParam(responseTableObj);
        hideLoading(intervalId);
    })
})

/**
 * 显示loading进度条
 * @param loadingValue  初始值
 * @param value 每次递增的值
 */
function showLoading(initValue, stepValue) {
    $("#paramProgressBar").show();
    var intervalId;
    var time   = initValue;
    intervalId = setInterval(function () {
        if (time < 100) {
            $("#paramProgressBar div.progress div.progress-bar")
                .html(time + "%")
                .css("width", time + "%");
            time += stepValue;
        } else {
            // 隐藏loading条
            hideLoading(intervalId);
        }
    }, 1000);
    return intervalId;
}
/**
 * 隐藏loading条
 */
function hideLoading(intervalId) {
    clearInterval(intervalId);
    $("#paramProgressBar div.progress div.progress-bar")
        .html(0 + "%")
        .css("width", 0 + "%");
    $("#paramProgressBar").hide();
}

/**
 * 给input框添加required属性
 * @type {*|jQuery|HTMLElement}
 */

function addRequired() {
    $("input[class='form-control']").attr("required", "required");
}


var imageTemplate = $("<div class='item'><img src='{0}'/></div>");
var dotTemplate   = $("<li data-target='#carousel-example-generic' data-slide-to='{0}'></li>");


function addImage(imagePaths) {
    var imageArr = eval(imagePaths);
    for (var i = 0; i < imageArr.length; i++) {
        if (i == 0) {
            imageTemplate = "<img src='{0}' class='img-theme'/>";
        } else {
            imageTemplate = "<img src='{0}' class='img-theme'/>";
        }
        var img = replaceTheme(imageTemplate, basePath + "/static/images/bg/" + imageArr[i]);
        $("div.img-bg div").append(img);
    }
}

function addDot(imagePaths) {
    var imageArr = eval(imagePaths);
    for (var i = 0; i < imageArr.length; i++) {
        if (i == 0) {
            dotTemplate = "<li data-target='#carousel-example-generic' data-slide-to='{0}' class='active'></li>";
        } else {
            dotTemplate = "<li data-target='#carousel-example-generic' data-slide-to='{0}'></li>";

        }
        var dot_li = replaceTheme(dotTemplate, i);
        $("#dot-list").append("<div></div>").append(dot_li);
    }
}

/**
 * 模板替换方法
 * @param template
 * @param param
 * @returns {void|XML|string}
 */
function replaceTheme(template, param) {
    var pattern = /\{(\d*)\}(?!})/g;
    return template.replace(pattern, param);
}

/**
 * 改变主题并设置北京属性的值
 * @param themeName 主题的图片名字
 */
function changeTheme(themeName) {
    $("div.img-bg-prev").css("background-image", 'url(' + themeName + ')');
    $("div.theme-footer div button.btn.btn-primary").attr("bgsrc", themeName);
}

/**
 * 隐藏主题选择框
 */
function hide_image_Carousel() {
    $image_Carousel.slideUp();
    flag = false;
}

/**
 * 显示 主题选择框
 */
function show_image_Carousel() {
    $image_Carousel.slideDown();
    flag = true;
}


function joinTable(tableTemplateReplaced, obj) {

    var tableTitle  = '<table class="table"' + obj.type + '" table-striped col-lg-push-1">';
    var tableFooter = '</tbody></table>';
    return tableTitle + obj.tableClassName + obj.className + obj.tableHeader + tableTemplateReplaced + tableFooter;

}


/**
 * 根据bean的全限定名
 * @param beanName 实体类的全限定名 （包名+类名）
 *
 */
function getMethodParam(obj) {
    $.ajax({
        type      : "get",
        url       : basePath + "/api/getFiled",
        dataType  : 'json',
        data      : "classWholeName=" + obj.className,
        async     : false,
        beforeSend: function (XMLHttpRequest) {
            //ShowLoading();
        },
        success   : function (data) {
            obj.dataParam = data;
            /* if (data['result'] == "true") {
             requestDataParam = data['data'];
             } else {
             console.info(data['msg']);
             }*/
        },
        complete  : function (XMLHttpRequest, textStatus) { /*HideLoading();*/
        },
        error     : function () { /*请求出错处理*/
        }
    });
    var result = getDomTable(obj);
    $("#paramTable").append($(result));

}

/**
 * 获得响应参数的table 或者是 请求参数的table
 * @returns {string|*|void|XML|string}
 */
function getDomTable(obj) {
    var result = "";
    var index  = 1;
    $.each(obj.dataParam, function (key, value) {
        var paramJson = obj.tableBody;
        for (var j = 0; j < 6; j++) {
            if (j == 0) {
                paramJson = replaceTemp(paramJson, index, j);
                index++;
            } else if (j == 1) {
                paramJson = replaceTemp(paramJson, value, j)
            } else if (j == 2) {
                paramJson = replaceTemp(paramJson, key, j)
            } else if (j == 3) {
                paramJson = replaceTemp(paramJson, "M", j)
            } else if (j == 4) {
                if (obj.type == "request") {
                    paramJson = replaceTemp(paramJson, "", j)
                }
            } else if (j == 5) {
                paramJson = replaceTemp(paramJson, key, j)
            }
        }
        result += paramJson;
    })
    return joinTable(result, obj);
}

/**
 *
 * @param template
 * @param param 要替换的参数
 * @param i 要替换的数字
 * @returns {string|void|XML}
 */
function replaceTemp(template, param, i) {
    var regex = "{" + i + "}";
    return template.replace(regex, param);
}

/**
 * 是否必须出现
 * @param me
 */
function appearNecessary(me) {
    // 类名
    var className = $(me).attr("class");
    if (className == "active text-center") {
        $(me).html("M");
        $(me).attr("class", "danger text-center");
    } else {
        $(me).html("O");
        $(me).attr("class", "active text-center");

    }
}
/**
 * 点击 X 删除元素
 * @param me
 */
function deleteTd(me) {
    if ($(me).attr("class") == "btn btn-danger glyphicon glyphicon-remove") {
        $(me).attr("class", "btn btn-success glyphicon glyphicon-ok");
    } else {
        var indexTds = $("#paramTable").find(me)
            .parent()
            .parent()
            .parent()
            .find("tr")
        $(me).parent().parent().remove();
        // 删除元素后修改序列
        $.each($(indexTds).find("td:first"), function (idx, indexTd) {
            $(indexTd).html(idx + 1);
        })

    }
}

/**
 * 修改表格
 * @param me
 */
function updateTd(me) {
    var $editField = $(me).parent().parent().find("*[class='form-control']");
    if ($editField.attr("readonly") == "readonly") {
        $editField.removeAttr("readonly", "");
        $(me).attr("class", "btn btn-success glyphicon glyphicon-ok")
    } else {
        $editField.attr("readonly", "readonly");
        $(me).attr("class", "btn btn-warning glyphicon glyphicon-pencil")
    }
}

var params_names_arr = [
    "paramIdentifying",
    "paramName",
    "appearNecessary",
    "defaultValue",
    "paramRequestDescription"];


/**
 *
 * @param dom   dom对象
 * @param i for循环的值
 * @param j 数组【j】的下标值
 */
function convertValue(domObj, i, j) {

}

/**
 * ajax 提交表单
 */
function addParam() {


    /*
     '<td class="success"><input class="form-control" type="text" value="{1}" readonly="readonly"/></td>' +
     '<td class="warning"><input class="form-control" type="text" value="{2}" readonly="readonly"/></td>' +
     '<td class="danger text-center" onclick="appearNecessary(this)">{3}</td>' +
     '<td class="info"><textarea class="form-control" readonly="readonly">{4}</textarea></td>' +
     '<td class="success"><textarea class="form-control" readonly="readonly">{5}</textarea> <!--<input class="form-control" type="text" value="{5}" readonly="readonly"/>--></td>' +
     */
    /* var paramIdentifying        =
     var paramName               =
     var appearNecessary         =
     var defaultValue            =
     var paramRequestDescription =*/

    var objParam          = {
        param: []
    };
    var paramClassNameArr = [];
    $.each($("#paramTable").find("table").find("thead").find("tr:first td"), function (idx, className) {
        paramClassNameArr[idx] = $(className).html()
    })
    console.info(paramClassNameArr);

    $.each($("#paramTable").find("table").find("tbody"), function (idxtb, tbody) {
        $.each($(tbody).find("tr"), function (idxtr, trs) {
            var paramsArr        = [];
            var params_value_arr = [];
            for (var i = 0; i < $(trs).find("td").length; i++) {
                if ($($(trs).find("td")[i]).attr("class")) {
                    params_names_arr[i] = getDomValueByDom(($(trs).find("td")[i]));
                }
            }
            objParam.param[idxtr] = params_names_arr;

        })
    })

    console.info(objParam)

    var url            = basePath + "/api/add";
    var apiType        = getDomValueById("apiType");
    var apiTitle       = getDomValueById("apiTitle");
    var apiSignature   = getDomValueById("apiSignature");
    var apiDescription = getDomValueById("apiDescription");
    var apiDemo        = getDomValueById("apiDemo");
    var apiRemark      = getDomValueById("apiRemark");

    $.ajax({
        type      : "post",
        url       : url,
        async     : false,
        dataType  : 'json',
        data      : {

            "apiType"       : apiType,
            "apiTitle"      : apiTitle,
            "apiSignature"  : apiSignature,
            "apiDescription": apiDescription,
            "apiDemo"       : apiDemo,
            "apiRemark"     : apiRemark,

        },
        beforeSend: function (XMLHttpRequest) {

        }, success: function (data) {

        }
        , complete: function (XMLHttpRequest, textStatus) {

        }
    })
}

function getDomValueById(id) {
    // 转成 dom 对象
    var $tag    = $("#" + id);
    var tagName = $tag[0].tagName;
    if (tagName == "INPUT") {
        return $tag.val();
    } else if (tagName == "TEXTAREA") {
        return $tag.html();
    } else {
        return $tag.html();
    }
}

/**
 * 根据dom对象查找元素
 * @param domObj
 */
function getDomValueByDom(domObj) {
    if ($(domObj).attr("class") == "danger text-center") {
        return $(domObj).html();
    }
    var $tag    = $(domObj).children();
    var tagName = $tag[0].tagName;
    if (tagName == "INPUT") {
        return $tag.val();
    } else if (tagName == "TEXTAREA") {
        return $tag.html();
    } else {
        return $tag.html();
    }
}
/**
 * 切换背景图片
 */
function changeBackgroundImg(me) {
    var imgsrc = $(me).attr("bgsrc");
    $("body").css("background-image", 'url(' + imgsrc + ')');
    hide_image_Carousel();
}